package net.da.core.bof.spi.local;

import net.da.core.bof.ApplicationSession;
import net.da.core.bof.PersistentObject;
import net.da.core.entity.PersistentObjectEntity;
import net.da.core.exception.DaException;
import net.da.core.manager.BusinessObjectManager;

public abstract class PersistentObjectImpl<E extends PersistentObjectEntity> extends DaObjectImpl implements
        PersistentObject {

    protected BusinessObjectManager businessObjectManager;

    private E entity;

    public PersistentObjectImpl() {
        super();
    }

    public PersistentObjectImpl(E entity) {
        setEntity(entity);
    }

    public E getEntity() {
        return entity;
    }

    public final void setEntity(E entity) {
        this.entity = entity;
    }

    public Class getEntityClass() {
        return PersistentObjectEntity.class;
    }

    public Integer getId() {
        return entity.getId();
    }

    public void destroy() {
        businessObjectManager.remove(this);
    }

    public boolean fetch(String string) {
        return true;
    }

    public void delete() {
        entity.setDeleted(true);
    }

    public final boolean isDirty() {
        throw new UnsupportedOperationException();
    }

    public final boolean isNew() {
        return entity.getId() == null ? true : false;
    }

    protected abstract void preSaveValidation() throws DaException;

    public void save(ApplicationSession session) throws DaException {
        preSaveValidation();
        businessObjectManager.save(this);
    }

    public void setPersistenceManager(BusinessObjectManager businessObjectManager) {
        this.businessObjectManager = businessObjectManager;
    }

    public void setBusinessObjectFactory(BusinessObjectManager businessObjectManager) {
        this.businessObjectManager = businessObjectManager;
    }
}
